<?php

namespace App\Http\Controllers;

use App\Helpers\ResponseEnum;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CommonController extends Controller
{
    /**
     * 文件上传
     * @param Request $request
     * @return JsonResponse
     */
    public function upload(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'file' => 'required|file|max:10240', // 最大10MB文件限制
        ]);
        if ($validator->fails()) {
            return $this->fail(ResponseEnum::HTTP_ERROR, '文件未传入');
        }
        $file = $request->file('file'); // 获取文件实例
        $filename = time() . '_' . $file->getClientOriginalName(); // 生成文件名，避免重名问题
        $path = $file->storeAs('images/' . date('Ymd'), $filename, 'public'); // 存储文件到public磁盘的uploads文件夹下，并返回路径信息（可选）或文件名（可选）

        return $this->success($path);
    }
}
